package com.mingtu.jgspatrol.activity;

import static com.mingtu.jgspatrol.utils.MyConstant.ItemDecorationSpaces;

import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.hjq.gson.factory.GsonFactory;
import com.luck.picture.lib.entity.LocalMedia;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.CenterPopupView;
import com.lxj.xpopup.util.XPopupUtils;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.mingtu.common.Eventbus.MyEventBus;
import com.mingtu.common.base.BaseApplication;
import com.mingtu.common.callback.StringDialogCallback;
import com.mingtu.common.utils.ActivityUtil;
import com.mingtu.common.utils.Constant;
import com.mingtu.common.utils.GridSpacingItemDecoration;
import com.mingtu.common.utils.MyLogUtil;
import com.mingtu.common.utils.MyUtills;
import com.mingtu.common.utils.ScreenUtils;
import com.mingtu.jgspatrol.R;
import com.mingtu.jgspatrol.adapter.ApprovePictureVideoVoiceAdapter;
import com.mingtu.jgspatrol.adapter.ApproveProgressAdapter;
import com.mingtu.jgspatrol.base.MyBaseActivity;
import com.mingtu.jgspatrol.bean.ApproveDetailsBean;
import com.mingtu.jgspatrol.databinding.ActivityApproveDetailsBinding;
import com.mingtu.jgspatrol.databinding.ApproveMemoPopupBinding;
import com.mingtu.jgspatrol.utils.MyConstant;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class ApproveDetailsActivity extends MyBaseActivity<ActivityApproveDetailsBinding> {
    private ArrayList<LocalMedia> selectPictureList;
    private ApprovePictureVideoVoiceAdapter pictureVideoVoiceAdapter2;
    private List<ApproveDetailsBean.DataBean.AuditTaskAttachEntityListBean> DataBean = new ArrayList<>();
    private List<ApproveDetailsBean.DataBean.AuditTaskDetailEntityListBean> DataBean2 = new ArrayList<>();
    private ApproveProgressAdapter approveProgressAdapter;
    private String describe;
    private String approveId;
    private int status = 1;
    private String detailId;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_approve_details;
    }

    @Override
    protected void initView() {
        setModuleTitle("审批详情");
    }

    @Override
    protected void initData() {
        pictureVideoVoiceAdapter2 = new ApprovePictureVideoVoiceAdapter(context, DataBean, ScreenUtils.isTablet());
        GridLayoutManager layoutManager = new GridLayoutManager(context, 3);//第二个参数为网格的列数
        binding.recycler.setLayoutManager(layoutManager);
        binding.recycler.addItemDecoration(new GridSpacingItemDecoration(3, SizeUtils.dp2px(ItemDecorationSpaces), false));
//        recycler.setHasFixedSize(false);
        binding.recycler.setAdapter(pictureVideoVoiceAdapter2);
        pictureVideoVoiceAdapter2.setOnItemClickListener(new ApprovePictureVideoVoiceAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                BaseApplication.initPreviewModel().startActivityPreview(position, false, selectPictureList);
            }
        });


        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context);
        binding.recyclerProgress.setLayoutManager(linearLayoutManager);

        approveProgressAdapter = new ApproveProgressAdapter(context, DataBean2);
        binding.recyclerProgress.setAdapter(approveProgressAdapter);

        addClickListener(this, binding.butAgree, binding.butDisagree);

    }

    @Override
    protected void getData() {
        approveId = getIntent().getStringExtra("approveId");
        status = getIntent().getIntExtra("status", 0);
        int type = getIntent().getIntExtra("type", 0);
        //只有首页审批领导端口进入详情的时候，才显示审批操作
        if (status == 0 && type == 0) {
            binding.layoutBottom.setVisibility(View.VISIBLE);
        } else {
            binding.layoutBottom.setVisibility(View.GONE);
        }

        approveDetails(approveId);

    }


    /**
     * 审批详情
     *
     * @param approveId
     */
    private void approveDetails(String approveId) {

        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("taskId", approveId);
        String str = GsonUtils.toJson(hashMap);
        OkGo.<String>post(MyConstant.POST_APPROVE_DETAILS + "/" + approveId)
                .tag(this)
                .upJson(str)
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {

                            try {
                                Gson gson = GsonFactory.getSingletonGson();
                                ApproveDetailsBean approveDetailsBean = new ApproveDetailsBean();
                                approveDetailsBean = gson.fromJson(result, ApproveDetailsBean.class);

                                ApproveDetailsBean.DataBean dataBean = approveDetailsBean.getData();
                                if (dataBean != null) {
                                    List<ApproveDetailsBean.DataBean.AuditTaskAttachEntityListBean> attachEntityListBeans = dataBean.getAuditTaskAttachEntityList(); //附件
                                    List<ApproveDetailsBean.DataBean.AuditTaskDetailEntityListBean> detailEntityListBeans = dataBean.getAuditTaskDetailEntityList(); //审批流程

                                    String approveName = dataBean.getAuditName();
                                    String status = dataBean.getStatus(); //状态 0:待审批1：已通过2：已拒绝
                                    String applyUserName = dataBean.getApplyUserName();
                                    String createTime = dataBean.getCreateTime();
                                    String deptName = dataBean.getDeptName();
                                    String memo = dataBean.getMemo();
                                    detailId = dataBean.getDetailId();
                                    if (!StringUtils.isEmpty(approveName)) {
                                        binding.tvApproveType.setText(approveName);
                                    }
                                    if (status.equals("0")) {
                                        binding.tvApproveStatus.setText("待审批");
                                        binding.tvApproveStatus.setTextColor(context.getResources().getColor(R.color.main_color_3aa));
                                        binding.tvApproveStatus.setBackground(context.getDrawable(R.drawable.shape_bg_approve_status1));

                                    } else if (status.equals("1")) {
                                        binding.tvApproveStatus.setText("已通过");
                                        binding.tvApproveStatus.setTextColor(context.getResources().getColor(R.color.bg_color_f7c));
                                        binding.tvApproveStatus.setBackground(context.getDrawable(R.drawable.shape_bg_approve_status2));

                                    } else if (status.equals("2")) {
                                        binding.tvApproveStatus.setText("已拒绝");
                                        binding.tvApproveStatus.setTextColor(context.getResources().getColor(R.color.bg_color_dc6));
                                        binding.tvApproveStatus.setBackground(context.getDrawable(R.drawable.shape_bg_approve_status3));
                                    }

                                    if (!StringUtils.isEmpty(applyUserName)) {
                                        binding.tvApproveName.setText("申请人：" + applyUserName);
                                    }
                                    if (!StringUtils.isEmpty(createTime)) {
                                        binding.tvTime.setText("申请时间：" + createTime);
                                    }
                                    if (!StringUtils.isEmpty(deptName)) {
                                        binding.tvDepart.setText("所属部门：" + deptName);
                                    }

                                    if (!StringUtils.isEmpty(memo)) {
                                        binding.tvContent.setText("申请内容：" + memo);
                                    }

                                    //附件逻辑
                                    selectPictureList = new ArrayList<>();
                                    if (attachEntityListBeans != null) {
                                        if (attachEntityListBeans.size() > 0) {
                                            DataBean.addAll(attachEntityListBeans);
                                            for (int i = 0; i < DataBean.size(); i++) {
                                                ApproveDetailsBean.DataBean.AuditTaskAttachEntityListBean listBean = DataBean.get(i);
                                                String url = listBean.getUrl();
                                                LocalMedia localMedia = LocalMedia.generateHttpAsLocalMedia(url);
                                                selectPictureList.add(localMedia);
                                            }

                                            pictureVideoVoiceAdapter2.upData(DataBean);
                                        }
                                    }

                                    //流程逻辑
                                    ApproveDetailsBean.DataBean.AuditTaskDetailEntityListBean detailEntityListBean = new ApproveDetailsBean.DataBean.AuditTaskDetailEntityListBean();
                                    detailEntityListBean.setUserName(applyUserName);
                                    detailEntityListBean.setAuditTime(createTime);
                                    detailEntityListBean.setStatus("3"); //自定义的  发起审批标记
                                    detailEntityListBeans.add(0, detailEntityListBean);

                                    approveProgressAdapter.upData(detailEntityListBeans);
                                }
                            } catch (JsonSyntaxException e) {
                                e.printStackTrace();
                            }


                        }
                    }
                });
    }


    /**
     * 审批
     */
    private void approveEvent() {

        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("auditMemo", describe);
        if (!StringUtils.isEmpty(detailId)) {
            hashMap.put("detailId", Integer.parseInt(detailId));
        }
        hashMap.put("status", status);
        String str = GsonUtils.toJson(hashMap);
        OkGo.<String>post(MyConstant.POST_APPROVE_SUBMIT)
                .tag(this)
                .upJson(str)
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {
                            JSONObject jsonObject = JSON.parseObject(result);
                            String msg = jsonObject.getString("msg");
                            if (msg.equals(Constant.RESULT_SUCCESS)) {
                                ToastUtils.showLong("审批成功！");
                                binding.layoutBottom.setVisibility(View.GONE);
                                EventBus.getDefault().post(new MyEventBus(MyConstant.REFRESH_APPROVE_DATA));
                            }
                        }
                    }
                });
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.but_agree:
                status = 1;
                break;
            case R.id.but_disagree:
                status = 2;
                break;
        }
        new XPopup.Builder(ActivityUtil.getTopActivity())
                .moveUpToKeyboard(false) //如果不加这个，评论弹窗会移动到软键盘上面
                .isViewMode(true)
                .isDestroyOnDismiss(false) //对于只使用一次的弹窗，推荐设置这个
                .asCustom(new CenterPopup(ActivityUtil.getTopActivity()))
                .show();
    }

    /**
     * 中间弹出的pop
     */
    public class CenterPopup extends CenterPopupView implements View.OnClickListener {
        private ApproveMemoPopupBinding popupBinding;

        public CenterPopup(@NonNull Context context) {
            super(context);

        }

        @Override
        protected int getImplLayoutId() {
            return R.layout.approve_memo_popup;
        }

        @Override
        protected void onCreate() {
            super.onCreate();
            popupBinding = ApproveMemoPopupBinding.bind(centerPopupContainer.getChildAt(0));

            popupBinding.butCancle.setOnClickListener(this);
            popupBinding.butCommit.setOnClickListener(this);

            popupBinding.editDescribe.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                }

                @Override
                public void afterTextChanged(Editable s) {
                    MyLogUtil.e("MyTest", "afterTextChanged==" + s.toString());
                    describe = MyUtills.getEditText(popupBinding.editDescribe);
                    popupBinding.editDescribe.setSelection(describe.length());
                }
            });


        }

        @Override
        protected void onShow() {
            super.onShow();
        }

        @Override
        protected void onDismiss() {
            KeyboardUtils.hideSoftInput(ActivityUtil.getTopActivity());
        }

        @Override
        protected int getMaxHeight() {
            return (int) (XPopupUtils.getScreenHeight(getContext()) * .7f);
        }

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.but_cancle:
                    dismiss();
                    break;
                case R.id.but_commit:
                    dismiss();
                    approveEvent();
                    break;

            }
        }
    }


}